package com.gouying.web.listener;

import com.gouying.to.mq.OrderTo;
import com.gouying.to.mq.StockLockedTo;
import com.gouying.web.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    //库存锁定延时时间到，检查库存锁定是否需要解锁
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到库存解锁的消息……");
        try {
            //当前消息是否被第二次及以后（重新）派发过来了
            //Boolean redelivered = message.getMessageProperties().getRedelivered();getRedelivered
            wareSkuService.unLockStock(to);
            //回复消息消费成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //有异常，消息就重新回队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }

    }

    //订单服务自身直接关闭订单后向队列发送的消息，解锁库存
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭准备解锁库存……");
        try {
            wareSkuService.unLockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            //有异常，消息就重新回队列等待下一次重新解锁
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
